package cn.hfjava.kz.service.impl;

import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.entity.dto.ForgetPasswordDto;
import cn.hfjava.kz.entity.dto.UpdatePasswordDTO;
import cn.hfjava.kz.entity.dto.UserQueryDTO;
import cn.hfjava.kz.entity.vo.PageVO;
import cn.hfjava.kz.entity.vo.UserVO;
import cn.hfjava.kz.utils.SendMessage;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hfjava.kz.entity.po.User;
import cn.hfjava.kz.service.UserService;
import cn.hfjava.kz.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lds
 * @description 针对表【users(用户表)】的数据库操作Service实现
 * @createDate 2024-07-09 11:22:19
 */
@Service
//@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    public PageVO<UserVO> findByPage(UserQueryDTO userQueryDto) {
        // 1、开启分页
        PageHelper.startPage(userQueryDto.getCurPage(), userQueryDto.getPageSize());

        // 2、根据组合条件分页查询管理员用户基本信息
        List<UserVO> userVoList = userMapper.getUserVoList(userQueryDto);

        // 获取总记录数
        long total = userMapper.getUserVoCount(userQueryDto);

        // 封装分页对象
        PageVO pageVO = new PageVO<>(userQueryDto.getCurPage(),userQueryDto.getPageSize(),total,userVoList);

        // 返回分页对象
        return pageVO;
    }

    @Override
    public SaResult forgetPassword(ForgetPasswordDto forgetPasswordDto) {
        if(forgetPasswordDto!=null){
            QueryWrapper<User>wrapper=new QueryWrapper<User>().
                    eq("username",forgetPasswordDto.getUsername()).
                    eq("phone",forgetPasswordDto.getPhone());
            User user=getOne(wrapper);
            if(user!=null){
                //生成随机4位数字
                String code=String.valueOf((int)((Math.random()*9+1)*1000));
                //保存到redis
                redisTemplate.opsForValue().set(user.getPhone()+"forgetPassword",code,5, TimeUnit.MINUTES);
                SendMessage sendMessage=new SendMessage();
                sendMessage.senMsessage(forgetPasswordDto.getPhone(),code);
                user.setPassword("");
                return SaResult.ok("修改验证码发送成功").setData(user);
            }
        }
        return SaResult.error("修改验证码发送失败");
    }

    @Override
    public SaResult verifyCode(ForgetPasswordDto forgetPasswordDto) {
        if(forgetPasswordDto!=null){
//            redis获取验证码
            String code=(String)redisTemplate.opsForValue().get(forgetPasswordDto.getPhone()+"forgetPassword");
            if(!StrUtil.isEmpty(code)&&code.equals(forgetPasswordDto.getCode())){
                redisTemplate.delete(forgetPasswordDto.getPhone()+"forgetPassword");
                redisTemplate.opsForValue().set(forgetPasswordDto.getPhone()+"updateCode",forgetPasswordDto.getPhone(),5, TimeUnit.MINUTES);
                return SaResult.ok("验证码正确");
            }
        }
        return SaResult.error("验证码错误");
    }

    @Override
    public SaResult updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        if(updatePasswordDTO!=null){
            String updateCode = (String) redisTemplate.opsForValue().get(updatePasswordDTO.getPhone() + "updateCode");
            if(updateCode.equals(updatePasswordDTO.getPhone())){
                if(!updatePasswordDTO.getNewPassword().equals(updatePasswordDTO.getPassword())){
                    return SaResult.error("新密码不能与旧密码相同");
                }
                LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
                lqw.eq(User::getPhone, updatePasswordDTO.getPhone());
                User user = getOne(lqw);
                if(user!=null){
                    user.setPassword(passwordEncoder.encode(updatePasswordDTO.getNewPassword()));
                    updateById(user);
                    return SaResult.ok("修改密码成功");
                }
            }
        }
        return SaResult.error("修改密码失败");
    }
}




